package com.agrimall.servlet.client;

import com.agrimall.entity.Announcement;
import com.agrimall.entity.User;
import com.agrimall.mapper.AnnouncementMapper;
import com.agrimall.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 公告列表AJAX接口
 */
@WebServlet("/client/announcement/listAjax")
public class AnnouncementListAjaxServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            // 获取当前登录用户
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                out.print("{\"success\":false,\"message\":\"未登录\"}");
                return;
            }
            
            // 根据用户类型确定公告类型：0-普通用户，1-商户
            Integer announcementType = user.getUserType() == 1 ? 1 : 0;
            
            // 查询公告列表（最多10条）
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                AnnouncementMapper mapper = sqlSession.getMapper(AnnouncementMapper.class);
                List<Announcement> announcements = mapper.selectVisibleByType(announcementType, 0, 10);
                
                // 构建JSON响应
                StringBuilder json = new StringBuilder("{\"success\":true,\"data\":[");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                
                for (int i = 0; i < announcements.size(); i++) {
                    Announcement ann = announcements.get(i);
                    if (i > 0) json.append(",");
                    json.append("{");
                    json.append("\"announcementId\":").append(ann.getAnnouncementId()).append(",");
                    json.append("\"title\":\"").append(escapeJson(ann.getTitle())).append("\",");
                    json.append("\"content\":\"").append(escapeJson(ann.getContent())).append("\",");
                    json.append("\"createTime\":\"").append(sdf.format(ann.getCreateTime())).append("\"");
                    json.append("}");
                }
                json.append("]}");
                
                out.print(json.toString());
            } finally {
                sqlSession.close();
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"查询公告失败：" + escapeJson(e.getMessage()) + "\"}");
        }
    }
    
    private String escapeJson(String str) {
        if (str == null) return "";
        return str.replace("\\", "\\\\")
                  .replace("\"", "\\\"")
                  .replace("\n", "\\n")
                  .replace("\r", "\\r")
                  .replace("\t", "\\t");
    }
}

